
import jieba
from wordcloud import WordCloud
import re
import  numpy as np
from PIL import Image

import matplotlib.pyplot as plt


#生成词云函数
def generate_wordcloud(text):

    list = []
    text = open(text, 'r', encoding='GBK').read()
    with open('stopword.txt', 'r', encoding='utf-8') as f:
        for line in f:
            list.append(line.strip('\n'))
    # print(list)


    cut_text = jieba.cut(text)
    # print(type(cut_text))
    # print(next(cut_text))
    # print(next(cut_text))
    # 3.以空格拼接起来
    result = " ".join(cut_text)
    image=np.array(Image.open('star.jpg'))

    stopwords = set(list)

    # print(result)
    # 4.生成词云
    wc = WordCloud(
        font_path='simhei.ttf',  # 字体路劲
        background_color='white',  # 背景颜色
        width=1000,
        height=600,
        max_font_size=100,  # 字体大小
        min_font_size=20,
        # mask=plt.imread('xin.jpg'),  #背景图片
        max_words=20,
        font_step=2,
        stopwords=stopwords,  # 设置停用词
        mask= image

    )
    wc.generate(result)
    wc.to_file('result.png')  # 图片保存

    # 5.显示图片
    plt.figure('result')  # 图片显示的名字
    plt.imshow(wc)
    plt.axis('off')  # 关闭坐标
    plt.show()


#生成修仙小说词云
generate_wordcloud('XX.txt')
#生成言情小说词云
generate_wordcloud('YQ.txt')


